package csu.webcourse.mypetstore.web.servlet;

import csu.webcourse.mypetstore.domain.Account;
import csu.webcourse.mypetstore.domain.Cart;
import csu.webcourse.mypetstore.domain.CartItem;
import csu.webcourse.mypetstore.domain.Item;
import csu.webcourse.mypetstore.service.CartService;
import csu.webcourse.mypetstore.service.LogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Iterator;

public class RemoveCartItemServlet extends HttpServlet {
    private static final String ERROR_FORM = "/WEB-INF/jsp/common/error.jsp";
    private static final String CART_FORM = "/WEB-INF/jsp/cart/cart.jsp";
    CartService cartService;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String userId=req.getParameter("userId");
        String workingItemId = req.getParameter("workingItemId");
        HttpSession session = req.getSession();
        cartService = new CartService();
        Cart cart = (Cart) session.getAttribute("cart");

        Account account = (Account) session.getAttribute("loginAccount");
        if (account != null) {
            HttpServletRequest httpRequest = req;
            String strBackUrl = "http://" + req.getServerName() + ":" + req.getServerPort()
                    + httpRequest.getContextPath() + httpRequest.getServletPath() + "?" + (httpRequest.getQueryString());

            LogService logService = new LogService();
            //最后加入的信息“XXXXX”应当为该界面的信息以及一些商品信息
            String logInfo = logService.logInfo(" ") + strBackUrl + "用户删除" + workingItemId + "商品";
            logService.insertLogInfo(account.getUsername(), logInfo);
        }

        Item item = cartService.removeItemById(cart, workingItemId);

        if (item == null) {
            session.setAttribute("errorMsg", "Attempted to remove null CartItem from Cart.");

            if (account != null) {
                HttpServletRequest httpRequest = req;
                String strBackUrl = "http://" + req.getServerName() + ":" + req.getServerPort()
                        + httpRequest.getContextPath() + httpRequest.getServletPath() + "?" + (httpRequest.getQueryString());

                LogService logService = new LogService();
                //最后加入的信息“XXXXX”应当为该界面的信息以及一些商品信息
                String logInfo = logService.logInfo(" ") + strBackUrl + "用户试图删除空商品";
                logService.insertLogInfo(account.getUsername(), logInfo);
            }

            req.getRequestDispatcher(ERROR_FORM).forward(req, resp);
        }

        //用户登陆后须对数据库进行操作
        if(userId!=null&&!userId.equals("")){
            //更新数据库(删除userId对应信息后重新插入
            cartService.removeCartListASYNC(userId,workingItemId);
            System.out.println("delete by userId");

            Iterator<CartItem> cartItems = cartService.getAllCartItems(cart);
            while (cartItems.hasNext()) {
                CartItem cartItem = (CartItem) cartItems.next();
                String itemId = cartItem.getItem().getItemId();

                try {
                    String quantityString = req.getParameter(itemId);
                    int quantity = Integer.parseInt(quantityString);

                    cartService.setQuantityByItemId(cart, itemId, quantity);
                    System.out.println(quantity+"quantity");
                    if(quantity < 1) {
                        cartItems.remove();
                    }
                    cartService.insertCartList(itemId, userId);
                }catch (Exception e) {
                    e.printStackTrace();
                }
            }
            resp.sendRedirect("cartForm");
        }

        else {
            resp.sendRedirect("cartForm");
        }
    }
}
